﻿using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
using CreditAgricole.Framework;

namespace CreditAgricole.CommonElements.MEPWFApprovedEventReceiver
{
    /// <summary>
    /// List Workflow Events
    /// </summary>
    public class MEPWFApprovedEventReceiver : SPWorkflowEventReceiver
    {

        //CAML query to retrieve task item based by WF instanceId  
        private const string WfInstanceQuery = @"<Where><Eq><FieldRef Name='WorkflowInstanceID'/><Value Type='GUID'>{0}</Value></Eq></Where>";
        private const string WorkflowTaskList = Constants.WorkflowTasksList;

        /// <summary>
        /// A workflow was completed.
        /// </summary>
        public override void WorkflowCompleted(SPWorkflowEventProperties properties)
        {
            base.WorkflowCompleted(properties);
            
            using (SPSite site = new SPSite(properties.WebUrl))
            using (SPWeb web = site.OpenWeb())
            {                
                // Query Workflow Task List  
                SPList wfTaskList = web.Lists[WorkflowTaskList];
                var items = wfTaskList.GetItems(new SPQuery()
                {
                    Query = string.Format(WfInstanceQuery, properties.InstanceId.ToString())
                });

                if (items.Count > 0)
                {
                    Guid listId = new Guid(items[0]["WorkflowListId"].ToString());
                    int itemId = (int)items[0]["WorkflowItemId"];
                    string workflowField = items[0]["WorkflowName"] as string;                    

                    // Get the List item on which the workflow run  
                    SPListItem item = web.Lists[listId].GetItemById(itemId);

                    // Get the workflow status
                    int status = Convert.ToInt32(item[workflowField]);

                    // Change content type
                    if (status == 16)
                    {
                        // Approved                        
                        item["ContentTypeId"] = item.ParentList.ContentTypes["Production Deployment Approved"].Id;
                        item.SystemUpdate();
                        CALoggingHelper.AddInformationEntry("Contenttype changed to Production Deployment Approved.");
                    }
                    else
                    {
                        // Rejected, cancelled, ...
                        item["ContentTypeId"] = item.ParentList.ContentTypes["Production Deployment Rejected"].Id;                                                                        
                        item.SystemUpdate();
                        CALoggingHelper.AddInformationEntry("Contenttype changed to Production Deployment Rejected.");
                    }

                    //SPSecurity.RunWithElevatedPrivileges(delegate() { item.ResetRoleInheritance(); });
                }
            }
        }
    }
}

